/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.plupload.util;

import com.plupload.model.TemporaryFile;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Usefull methods for file transfering
 *
 * @author Tiago Peres França
 * @version 0.2
 */
public class FileTransferer {
    /**
     * Transfer temporary files in a list to a definitive location, mantaining
     * its original name (in case it doesn't exist already). If the file already
     * exists a number will be writen before its extension. Example: If 
     * example.jpg already exists, example[1].jpg is created.
     * 
     * @param files list of temporary files
     * @param newPath path to the definitive location of the temporary files
     * @return list containing the definitive paths for each of the moved files 
     * 
     * @author Tiago Peres França
     * @version 0.2
     */
    public static List<String> transferTemporaryFiles(List<TemporaryFile> files, String newPath){
        List<String> paths = new ArrayList<String>();
        for (TemporaryFile file : files){
            File f = new File(file.getTemporaryPath());
            if (f.exists()){
                String newFilePath = newPath + System.getProperty("file.separator") + file.getName();
                int alreadyExists = 0;
                try{
                    while (!f.renameTo(new File(newFilePath))){
                        alreadyExists++;
                        String parts[] = newFilePath.split(".");
                        StringBuilder pathBuilder = new StringBuilder();
                        int i;
                        for (i = 0; i < parts.length - 1; i++){
                            pathBuilder.append(parts[i]);
                            pathBuilder.append(".");
                        }
                        pathBuilder.append("[");
                        pathBuilder.append(alreadyExists);
                        pathBuilder.append("]");
                        pathBuilder.append(parts[i]);
                        newFilePath = pathBuilder.toString();
                    }
                    paths.add(newPath);
                } catch (Exception ex){
                    ex.printStackTrace();
                }
            }
        }
        return paths;
    }
}
